//
//  MessageDetailViewController.swift
//  ezyform
//
//  Created by Hubert on 2022/5/9.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import HandyJSON

class MessageDetailViewController: BaseViewController {
    var id: String = ""
    //阅读通知后，刷新列表
    var refreshListBlock: (() -> Void)?
    var openFromNotifactionFlag: Bool = false//true表示从推送消息打开的此view，需要刷新外边的list列表
    var backToPreClosure: (() -> Void)?
    let customView = MessageDetailView()
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        loadData()
    }
    func initUI() {
        self.view = self.customView
        self.customView.setTitleInfo("Notification")
    }
    
    func loadData() {
        let service = NotificationService()
        service.setBlockAfterNetwork {[weak self] (result, _) in
            guard let self = self else { return }
            ModelViewUtil.shared.hideLoadingView()
            if let data = result as? [String: Any], let model = JSONDeserializer<NotificationModel>.deserializeFrom(dict: data) {
                let htmlBody = self.getHtmlBody(model)
                self.customView.webView.loadHTMLString(htmlBody, baseURL: nil)
                //设置角标
                MessageManager.shared.getUnreadCount()
                //从消息通知弹出框进来时，刷新列表list
                if self.openFromNotifactionFlag{
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "messageListRefreshNotification"), object: nil, userInfo: nil)
                }
                
                //从list进来是刷新list中的当前行
                self.refreshListBlock?()
            }
        } errorBlock: { (code, error) in
            ModelViewUtil.shared.hideLoadingView()
            Tool().showErrorInfo(code, error) {
                //从消息通知弹出框进来时，刷新列表list
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "messageListRefreshNotification"), object: nil, userInfo: nil)
            }
        }
        ModelViewUtil.shared.showLoadingView()
        service.getNotificationDetail(self.id)
    }
    private func getHtmlBody(_ model: NotificationModel)->String {
        self.customView.setTitleInfo(model.subject)
        var html = ""
        //添加html头信息
        html.append(contentsOf:"<html lang=\"en\">\n" +
                            "<head>\n" +
                            "    <meta charset=\"UTF-8\">\n" +
                            "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=2.0, user-scalable=yes\">\n" +
                            "    <title>" + model.subject + "</title>\n" +
                            "   <style>img{max-width:100%;width:auto;height:auto}</style>" +
                            "</head>\n" +
                            "<body>");
        html.append(contentsOf:"<h4 style=\"font-size: 18px;  color:rgb(54, 68, 82);  margin-top: 24px;\">" + model.subject + "</h4>\n");
        html.append(contentsOf:"<h5 style=\"font-size: 15px; color:rgba(130, 142, 153, 1);\">" + model.summary + "</h5>\n");
        html.append(contentsOf:"<div style=\"font-size: 15px; color:rgba(54, 68, 82, 1);\">\n");
        html.append(contentsOf: model.content + "\n");
        html.append(contentsOf:"<p style=\"text-align: left;font-size: 13px;color: rgba(177, 185, 195, 1);\">" + model.created_at + "</p >\n");
        html.append(contentsOf:"</div>\n");
                    //添加html结尾
        html.append(contentsOf:"</body>\n" +
                            "</html>");
        return html
    }
    
    @objc override func backToPre() {
        self.navigationController?.popViewController(animated: false)
        self.backToPreClosure?()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        self.toCheckPopNotification()
    }
    private func toCheckPopNotification(){
        if APPConfig.loginInfo.popNotificationList.count > 0{
            if let window = Tool.getKeyWindow(),let rootVC = window.rootViewController as? TabBarViewController {
                if rootVC.messageAlertView.superview == nil{
                    rootVC.pushImportantAlert(APPConfig.loginInfo.popNotificationList[0],newNotificationFlag: false)
                }
            }
        }
    }
}

